package com.ruoyi.project.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.base.util.GenCodeUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.domain.*;
import com.ruoyi.project.dto.ExcelimportPartstInfo;
import com.ruoyi.project.dto.PartstInfoDTO;
import com.ruoyi.project.mapper.BomInfoMapper;
import com.ruoyi.project.mapper.BomPartstRefMapper;
import com.ruoyi.project.mapper.CompomentInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mapper.PartstInfoMapper;
import com.ruoyi.project.service.IPartstInfoService;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.Name;

/**
 * 零件信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-08-27
 */
@Service
public class PartstInfoServiceImpl implements IPartstInfoService 
{
    @Autowired
    private PartstInfoMapper partstInfoMapper;

    @Autowired
    private BomInfoMapper bomInfoMapper;

    @Autowired
    private BomPartstRefMapper bomPartstRefMapper;

    @Autowired
    CompomentInfoMapper compomentInfoMapper;

    /**
     * 查询零件信息
     * 
     * @param id 零件信息主键
     * @return 零件信息
     */
    @Override
    public PartstInfo selectPartstInfoById(Long id)
    {
        return partstInfoMapper.selectPartstInfoById(id);
    }

    /**
     * 查询零件信息列表
     * 
     * @param partstInfo 零件信息
     * @return 零件信息
     */
    @Override
    public List<PartstInfo> selectPartstInfoList(PartstInfo partstInfo)
    {
        return partstInfoMapper.selectPartstInfoList(partstInfo);
    }

    /**
     * 新增零件信息
     * 
     * @param partstInfo 零件信息
     * @return 结果
     */
    @Override
    public int insertPartstInfo(PartstInfo partstInfo)
    {
        partstInfo.setCreateTime(DateUtils.getNowDate());
        return partstInfoMapper.insertPartstInfo(partstInfo);
    }

    /**
     * 修改零件信息
     * 
     * @param partstInfo 零件信息
     * @return 结果
     */
    @Override
    public int updatePartstInfo(PartstInfo partstInfo)
    {
        return partstInfoMapper.updatePartstInfo(partstInfo);
    }

    /**
     * 批量删除零件信息
     * 
     * @param ids 需要删除的零件信息主键
     * @return 结果
     */
    @Override
    public int deletePartstInfoByIds(Long[] ids)
    {
        return partstInfoMapper.deletePartstInfoByIds(ids);
    }

    /**
     * 删除零件信息信息
     * 
     * @param id 零件信息主键
     * @return 结果
     */
    @Override
    public int deletePartstInfoById(Long id)
    {
        return partstInfoMapper.deletePartstInfoById(id);
    }

    @Override
    public AjaxResult uploadBom(MultipartFile multipartFile, String projectNo, String buildNo) throws Exception {
        ExcelUtil<ExcelimportPartstInfo> util = new ExcelUtil<ExcelimportPartstInfo>(ExcelimportPartstInfo.class);
        List<ExcelimportPartstInfo> excelimportPartstInfoList = util.importExcel(multipartFile.getInputStream());
        int i=excelimportPartstInfoList.size()-1;
        for (;i>=0;i--){//获取最后空行
            if ("净重".equals(excelimportPartstInfoList.get(i).getTexture())){
                break;
            }
        }
        String bomNo = GenCodeUtils.getBOMNo();
        String compomentNo="";
        List<BomPartstRef> bomPartstRefList=new ArrayList<>();
        List<ProjectModelInfo> projectModelInfoList =new ArrayList<>();
        List<BomInfo> bomNoList=new ArrayList<>();
        for (int j = 0; j < i; j++) {
            ExcelimportPartstInfo excelimportPartstInfo=excelimportPartstInfoList.get(j);
            if (!"".equals(excelimportPartstInfo.getCompomentName())){//此行为构件行

               //查询是否有这个构件,如果没有报错
                CompomentInfo compomentInfo=partstInfoMapper.selectIsCompomentInfo(projectNo,excelimportPartstInfo.getCompomentName()
                ,excelimportPartstInfo.getSpecifications(),
                        excelimportPartstInfo.getTexture(),
                        excelimportPartstInfo.getLength(),
                        excelimportPartstInfo.getNetWeight()
                        );
                if (StringUtils.isNull(compomentInfo)){
                    //抛异常
                    throw new Exception(StringUtils.format("文件校验失败({})构件不存在。 ", excelimportPartstInfo.getCompomentName()));
                }
                CompomentInfo com=new CompomentInfo();
                com.setId(compomentInfo.getId());
                com.setSpecifications(excelimportPartstInfo.getSpecifications());
                com.setTexture(excelimportPartstInfo.getTexture());
                com.setLength(excelimportPartstInfo.getLength());
                com.setGrossWeight(excelimportPartstInfo.getGrossWeight());
                com.setNetWeight(excelimportPartstInfo.getNetWeight());
                compomentInfoMapper.updateCompomentInfo(com);
                bomNo = GenCodeUtils.getBOMNo();

                BomInfo bomInfo=new BomInfo();
                bomInfo.setBomNo(bomNo);
                bomInfo.setCompomentNo(compomentInfo.getCompomentNo());
                bomNoList.add(bomInfo);
                compomentNo=compomentInfo.getCompomentNo();
                List<String> floor = getFloor(excelimportPartstInfo);
                for (String f:floor){
                    ProjectModelInfo projectModelInfo=new ProjectModelInfo();
                    projectModelInfo.setProjectNo(projectNo);
                    projectModelInfo.setBuildNo(buildNo);
                    projectModelInfo.setFloor(f);
                    projectModelInfo.setBomNo(bomNo);
                    projectModelInfo.setCompomentNo(compomentNo);
                    projectModelInfoList.add(projectModelInfo);
                }
            }else{//创建bom信息
                //根据名称规格等查询是否有这个零件
                PartstInfo partstInfo=partstInfoMapper.selectIsPartstInfo(projectNo,excelimportPartstInfo.getPartsName(),
                        excelimportPartstInfo.getSpecifications(),
                        excelimportPartstInfo.getTexture(),
                        excelimportPartstInfo.getLength(),
                        excelimportPartstInfo.getNetWeight()
                        );
                if (StringUtils.isNull(partstInfo)){
                    throw new Exception(StringUtils.format("文件校验失败({})零件不存在。 ", excelimportPartstInfo.getPartsName()));
                }

                //已有BOM编号,零件编号,项目编号,自动生成BOM名称,拿到楼层信息,再写个for循环,将BOM,楼栋,楼层,构件编号分成条目

                BomPartstRef bomPartstRef=new BomPartstRef();
                bomPartstRef.setBomId(bomNo);
                bomPartstRef.setPartstId(partstInfo.getPartsNo());//设置零件主键
                bomPartstRef.setCount(excelimportPartstInfo.getCount());
                bomPartstRefList.add(bomPartstRef);

            }
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //数据校验完成,开始插入修改
        for (BomInfo bomInfo:bomNoList) {
            bomInfo.setProjectNo(projectNo);
            String string=bomInfoMapper.selectBomNameMax(projectNo,bomInfo.getCompomentNo());
            if (StringUtils.isEmpty(string))
                string="0";
            bomInfo.setBomName("BOM"+(Integer.parseInt(string)+1));
            bomInfo.setCreateTime(new Date());
            bomInfo.setCreateBy(user.getUserName());
            bomInfoMapper.insertBomInfo(bomInfo);
        }
        for (int j = 0; j < bomPartstRefList.size(); j++) {
            BomPartstRef bomPartstRef = bomPartstRefList.get(j);
            bomPartstRef.setCreateTime(new Date());
            bomPartstRef.setCreateBy(user.getUserName());
            bomPartstRefMapper.insertBomPartstRef(bomPartstRef);
        }
        for (int j = 0; j < projectModelInfoList.size(); j++) {
            ProjectModelInfo projectModelInfo = projectModelInfoList.get(j);
            partstInfoMapper.updatePartstModelInfo(projectNo,buildNo,projectModelInfo.getFloor(),projectModelInfo.getCompomentNo(),projectModelInfo.getBomNo());
        }
        return AjaxResult.success();
    }



    List <String>getFloor(ExcelimportPartstInfo excelimportPartstInfo){
        String partsName = excelimportPartstInfo.getPartsName();//楼栋信息
        String[] split = partsName.split(",");
        List<String> floor=new ArrayList<>();//楼层信息
        for (String s:split){
            if (s.indexOf('-')==-1){
                floor.add(s);
            }else {
                int start=0;
                int end=0;
                Pattern r = Pattern.compile("\\d+");
                Matcher m = r.matcher(s);
                if (m.find( )) {
                    start=Integer.parseInt(m.group(0));
                }
                if (m.find(m.end())) {
                    end= Integer.parseInt(m.group(0));
                }
                Pattern r1 = Pattern.compile("\\D+");
                Matcher m1 = r1.matcher(s.split("-")[0]);
                m1.find();
                String floorIdentification = m1.group(0);
                for (;start<=end;start++){
                    //floor.add(start+floorIdentification);
                    floor.add(start+floorIdentification);
                }
            }

        }
        return floor;
    }

    @Override
    public AjaxResult uploadpartst(MultipartFile multipartFile, String projectNo) throws Exception {
        ExcelUtil<PartstInfoDTO> util = new ExcelUtil<PartstInfoDTO>(PartstInfoDTO.class);
        List<PartstInfoDTO> partstInfoDTOList = util.importExcel(multipartFile.getInputStream());

        List<PartstInfoDTO> partstInfoDTOStream = partstInfoDTOList.stream().filter(p -> !"".equals(p.getPartsName()) && p.getCount() != null).collect(Collectors.toList());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        for (PartstInfoDTO p:partstInfoDTOStream){
            p.setProjectNo(projectNo);
            p.setPartsNo(GenCodeUtils.getPartstNo());
            p.setCreateBy(user.getUserName());
            p.setCreateTime(new Date());
            PartstInfo partstInfo=partstInfoMapper.selectPartstInfoByDTO(p);
            if (partstInfo==null){
                partstInfoMapper.insertPartstInfoDTO(p);
            }else{
                p.setId(partstInfo.getId());
                partstInfoMapper.updatePartstInfoDTO(p);
            }
        }

        return AjaxResult.success();
    }
}




























